const { ccclass, property } = cc._decorator;

@ccclass
export default class midPoint_Displacement extends cc.Component {

    ctx: cc.Graphics = null;
    @property
    displace = 0;
    @property
    detail = 1;

    cur_displace = 0;
    cur_detail = 1;

    p1 = cc.v2()
    p2 = cc.v2()
    onLoad() {
        let ctxNode = new cc.Node('ctxNode');
        ctxNode.parent = cc.director.getScene();
        ctxNode.position = cc.v2(0, 0);
        this.ctx = ctxNode.addComponent(cc.Graphics);
        this.ctx.lineWidth = 3;

        this.p1 = cc.v2(cc.winSize.width * 0.2, cc.winSize.height / 2)
        this.p2 = cc.v2(cc.winSize.width * 0.8, cc.winSize.height / 2)
        // this.detail = this.p1.sub(this.p2).mag()
        // this.displace = this.p1.sub(this.p2).mag()
        this.schedule(() => {
            this.draw();
        }, 0.1)
    }

    draw() {
        let ctx = this.ctx
        ctx.clear();
        this.drawLighting(
            this.p1,
            this.p2,
            this.cur_displace,
        );
    }
    // 中点位移算法
    // 参考https://krazydad.com/bestiary/bestiary_lightning.html
    drawLighting(p1, p2, displace) {
        // console.log('data', this.displace, this.detail)
        // console.log('drawLighting', p1, p2);
        let ctx = this.ctx;
        let detail = this.cur_detail;
        /**算出次数 */
        // let 

        /**递归法 */
        if (displace < detail) {
            ctx.moveTo(p1.x, p1.y);
            ctx.lineTo(p2.x, p2.y);
            ctx.strokeColor = cc.color(255, 255, 0);
            ctx.stroke();
        } else {
            let mid_x = (p2.x + p1.x) / 2;
            let mid_y = (p2.y + p1.y) / 2;
            mid_x += (Math.random() - 0.5) * displace;
            mid_y += (Math.random() - 0.5) * displace;
            this.drawLighting(p1, cc.v2(mid_x, mid_y), displace / 2);
            this.drawLighting(p2, cc.v2(mid_x, mid_y), displace / 2);
        }
    }

    setDisplacement(e) {
        this.cur_displace = e.progress * this.displace;
        // this.draw();
    }

    setDeltail(e) {
        // return
        this.cur_detail = e.progress * this.detail;
        this.cur_detail = this.cur_detail || 1;
        // this.draw();
    }

    update(dt) {

    }
}
